using Godot;
using System;

public partial class Sword : AnimatedSprite2D
{
	public Enemy enemy;

	public Player player;

	public Area2D area2D;

	public VisibleOnScreenNotifier2D visibleOnScreenNotifier2D;

	[Export]
	public int ThrowSpeed = 5;

	public bool IsThrow = false;

	public int direction = 1;
	public override void _Ready()
	{
		TopLevel = true;

		enemy = GetNode<Enemy>("/root/Main/Enemy");
		player = GetNode<Player>("/root/Main/Player");

		visibleOnScreenNotifier2D = GetNode<VisibleOnScreenNotifier2D>("VisibleOnScreenNotifier2D");
		visibleOnScreenNotifier2D.ScreenExited+=OnExitScreen;

		area2D = GetNode<Area2D>("Area2D");
		area2D.BodyEntered+=OnCollision;
		area2D.SetCollisionMaskValue(2,false);
	}

    private void OnCollision(Node2D body)
    {
        if(body.Name=="Player")
		{
			player.OnHurt();
		}
    }

    // Called every frame. 'delta' is the elapsed time since the previous frame.

    public override void _Process(double delta)
	{
		if(IsThrow)
		{
			Position += new Vector2(ThrowSpeed*direction,0);
		}
	}

	
    private void OnExitScreen()
    {
        IsThrow = false;
		Visible = false;
		area2D.SetCollisionMaskValue(2,false);
    }

	public void OnThrowSword()
	{
		GetNode<AudioStreamPlayer2D>("Music").Play();

		area2D.SetCollisionMaskValue(2,true);
		IsThrow = true;
		Visible = true;
		Position = enemy.Position;
		direction = player.Position.X-Position.X>0?1:-1;
		FlipV = direction > 0;
		Play();
	}
}
